import {
  getWinnowList,
  getWaitList,
  recommendTeacher,
  getMessage_count,
} from "@/static/js/quiz.js";
import { getUserInfo } from '@/static/js/user'
export default {
  data() {
    return {
      tipList: [
        {
          name: "财税专家回复",
        },
        {
          name: "快速解答",
        },
        {
          name: "服务品质保障",
        },
      ],
      askList: [],
      answerList: [],
      tabList: [
        {
          id: 1,
          name: "精选回答",
          type: 1,
          status: "more",
          page: 1,
          sort: "0",
          dataList: [],
        },
        {
          id: 2,
          name: "等你来答",
          type: 2,
          status: "more",
          page: 1,
          sort: "0",
          dataList: [],
        },
      ],
      current: 0,
      askShow: true,
      listStatus: "more",

      userInfo: {},

      query: {
        sort: 2, //推荐的数据
        page: 1,
        limit: 10,
      }, //请求参数
      tagsList: [
        {
          type: 2,
          name: "最新",
          disabled: true,
        },
        {
          type: 1,
          name: "最热",
          disabled: false,
        },
      ],
      isRefreshing: false, //界面下拉的状态

      teacherList: [],
      inviteValue: 0,
      activeStyle: {
        color: "#1C87F3",
        fontWeight: "bold",
        fontSize: "36rpx",
        transform: "scale(1.05)",
      },
      inactiveStyle: {
        color: "#333333",
        fontSize: "30rpx",
        transform: "scale(1)",
      },
      tokenFlag: false, //是否登录存在token
    };
  },
  methods: {
    // 获取未读消息通知
    getMessages() {
      getMessage_count({}).then((res) => {
        if (res.code == 1) {
          this.$store.state.inviteValue = res.data.dengnilaida;
        }
      });
    },
    //tab栏切换
    menuClick(e) {
      this.current = e.index;
      if (e.type == 1) {
        this.askShow = true;
        this.answerShow = false;
        this.getWinnowList();
      } else {
        this.askShow = false;
        this.answerShow = true;
        this.getWaitList();
      }
      if (this.tokenFlag) {
        this.getMessages();
      }
    },

    //切换精选回答最新，最热
    clickTags(item) {
      this.query.sort = item.type;
      this.query.page = 1;
      this.getWinnowList();
    },

    //快速提问
    toQuickAsk() {
      let token = uni.getStorageSync("token");
      if (!token) {
        uni.navigateTo({
          url: "/pages/login/login",
        });
        return;
      }
      uni.navigateTo({
        url: "../ask/index",
      });
    },
    jumpSearch() {
      let token = uni.getStorageSync("token");
      if (!token) {
        uni.navigateTo({
          url: "/pages/login/login",
        });
        return;
      }
      uni.navigateTo({
        url: "/quiz/search/index",
      });
    },
    // 去专家列表
    goExpertList() {
      uni.navigateTo({
        url: "/quiz/expertList/index",
      });
    },
    //去问答详情
    toDetail(val) {
      uni.navigateTo({
        url: "/quiz/askInfo/index?id=" + val.id,
      });
    },

    //前往我的问答
    goMyAskAnswers() {
      let token = uni.getStorageSync("token");
      if (!token) {
        uni.navigateTo({
          url: "/pages/login/login",
        });
        return;
      }
      uni.navigateTo({
        url: "/quiz/myAsk/index",
      });
    },

    //增加用户分析
    // userAnalysis() {
    //   getUserAnalysis({
    //     type: 2,
    //     m_id: 10,
    //   }).then((res) => {
    //     if (res.code == 1) {
    //       // console.log('用户分析成功');
    //     }
    //   });
    // },

    //获取推荐老师
    getTeacherList() {
      recommendTeacher().then((res) => {
        if (res.code == 1) {
          this.teacherList = res.data;
        }
      });
    },

    //精选回答列表
    getWinnowList() {
      getWinnowList(this.query).then((res) => {
        if (res.code === 1) {
          const newList = res.data;
          this.listStatus = newList.length >= this.query.limit ? "more" : "nomore";

          if (this.query.page === 1) {
            this.askList = [];
          }

          // 处理 first_answer 信息并构建 answerBean
          newList.forEach((val) => {
            let messageParts = [];
            let answerBean = null;

            val.first_answer?.forEach((answer, index) => {
              const bean = JSON.parse(answer.message);
              if (bean && index < 2) {
                if (!answerBean) {
                  answerBean = { ...bean, extendedData: { type: 1 } };
                }
                if (bean.extendedData.type === 1) {
                  messageParts.push(bean.message);
                } else if (bean.extendedData.type === 11) {
                  messageParts.push("[图片]");
                }
                if (index < 1) {
                  messageParts.push(",");
                }
              }
            });

            if (answerBean) {
              answerBean.message = messageParts.join('').trim();
            }

            // 将处理后的数据推入 askList，并移除重复项（基于 id）
            this.askList.push({
              title: val.title,
              nickname: val.nickname,
              add_time_text: val.add_time_text,
              page_view: val.page_view,
              answer: answerBean,
              avatar: val.avatar,
              id: val.id,
            });
          });

          // 使用 Set 和 Map 结构去除 askList 中的重复项
          this.askList = [...new Map(this.askList.map(item => [item.id, item])).values()];

          this.isRefreshing = false;
        }
      });
    },

    //等你来答列表
    getWaitList() {
      this.listStatus = "loading";
      getWaitList().then((res) => {
        if (res.code == 1) {
          this.answerList = res.data;
          this.listStatus = "nomore";
          this.isRefreshing = false;
        }
      });
    },

    //下拉刷新
    reload() {
      this.isRefreshing = true;
      this.query.page = 1;
      this.getWinnowList();
    },

    // 加载更多
    loadMore() {
      if (this.listStatus == "more") {
        this.query.page++;
        this.getWinnowList();
      }
    },

    //去老师主页
    goHome(item) {
      let token = uni.getStorageSync("token");
      if (!token) {
        uni.navigateTo({
          url: "/pages/login/login",
        });
        return;
      }
      uni.navigateTo({
        url: "/pages/my/homeCenter/taTeacherHome?id=" + item.user_id,
      });
    },

    //等你来答
    toAnswer(item) {
      console.log(this.userInfo.is_major);
      if (this.userInfo.is_major != 1) {
        uni.showModal({
          title: "温馨提示",
          content: "成为专业人士才可以回答问题哦~",
          confirmText: "去成为",
          confirmColor: "#1C87F3",
          success: function (res) {
            if (res.confirm) {
              this.$tools.msg('敬请期待')
              // uni.navigateTo({
              //   url: "pages/my/special/index",
              // });
            }
          },
        });
        return;
      }
      uni.navigateTo({
        url: "../chatRoom/index?id=" + item.id + "&type=true",
      });
    },


  },
  onLoad(e) {
    this.tokenFlag = uni.getStorageSync("token") ? true : false;
    this.getTeacherList();
    let hotAskStatus = uni.getStorageSync("hotAskStatus");
    if (hotAskStatus == 1) {
      this.current = 0;
      this.query.sort = 1;
    }


  },
  onShow() {
    let tokenFlag = uni.getStorageSync("token") ? true : false;
    if (tokenFlag) {
      // 获取个人信息  存到本地
      getUserInfo().then(res => {
        this.userInfo = res.data;
        uni.setStorageSync('userInfo', res.data)
      })
      this.getMessages();
    }
    if (this.current == 0) {
      this.getWinnowList();
    } else {
      this.getWaitList();
    }
  },
  onReady() { },
  onHide() {
    uni.removeStorageSync("hotAskStatus");
  },
};